<?php

namespace App\Service\Common;

use App\Jobs\Message\FsMessageJob;
use App\Library\Rms\RmsUserApi;
use App\Service\BaseService;

class FsCardService extends BaseService
{
    /**
     * 内容元素
     * @var array
     */
    private array $elementFields = [];

    private array $feishuIds = [];

    private string $path = 'CruiseCheck/feishu/notifyTemplate/generalV2.json';

    private string $module;

    private array $templateArr = [];

    const PATH_GENERAL_V3 = 'CruiseCheck/feishu/notifyTemplate/generalV3.json';

    /**
     * @param array $feishuIds
     */
    public function setFeishuIds(array $feishuIds): self
    {
        $this->feishuIds = array_merge($this->feishuIds, $feishuIds);
        $this->feishuIds = array_values(array_unique($this->feishuIds));

        return $this;
    }

    /**
     * @param string $path
     */
    public function setPath(string $path): self
    {
        $this->path = $path;
        return $this;
    }

    /**
     * @param string $module
     */
    public function setModule(string $module): self
    {
        $this->module = $module;
        return $this;
    }

    /**
     * 设置夸父员工的userIds
     * @param array $kfUserIds
     * @return $this
     */
    public function setKfUserIds(array $kfUserIds): self
    {
        // 转换成feishuIds
        $lists = (new RmsUserApi())->getUserInfoByIds($kfUserIds, ['feishuUserId'])['data'] ?? [];
        foreach ($lists as $v) {
            if (!in_array($v['feishuUserId'], $this->feishuIds)) {
                $this->feishuIds[] = $v['feishuUserId'];
            }
        }

        return $this;
    }

    /**
     * @param string $content
     * @return self
     */
    public function buildElementField(string $content): self
    {
        if ($content == 'notShow') {//不用显示
            return $this;
        }
        $this->elementFields[] = [
            'is_short' => (bool)$content,
            'text' => [
                'content' => $content,
                'tag'     => 'lark_md',
            ],
        ];

        return $this;
    }

    /**
     * 发送
     * @param array $params
     * @return void
     */
    public function send(array $params): void
    {
        $templateArr = json_decode(file_get_contents(resource_path($this->path)), true);
        $templateArr['elements'][0]['fields'] = $this->elementFields;

        $templateJson = vsprintf(json_encode($templateArr), $params);

        $this->baseSend(json_decode($templateJson, true));
    }

    /**
     * 底层发送
     * @param array $data
     */
    public function baseSend(array $data = []): void
    {
        if (!$data) {
            $data = $this->templateArr;
        }

        foreach ($this->feishuIds as $feishuId) {
            dispatch((new FsMessageJob($feishuId, $data, $this->module)));
        }
    }

    /**
     * 通配符data
     * @var array
     */
    private array $wildcardData;

    public function setWildCardData(array $data): self
    {
        $this->wildcardData = $data;

        return $this;
    }

    /**
     * 替换通配符
     * @param $param
     * @return array|string
     */
    private function replaceWildcard(&$param)
    {
        if (is_array($param)) {
            foreach ($param as &$v) {
                $this->replaceWildcard($v);
            }
        }

        if (!is_array($param)) {

            // 找到${xxx}，并替换成$this->>wildcardData中对应的key值
            preg_match_all('/\${(.*?)}/', $param, $arr);

            for ($i = 0; $i < count($arr[0]); $i++) {
                $param = str_replace($arr[0][$i], $this->wildcardData[$arr[1][$i]] ?? '', $param);
            }

//            dump($param);
        }

        return $param;
    }

    /**
     * 使用通配符替换$this->wildcardCard之后的array
     * @return self
     */
    public function replace(bool $buildElementFields = false): self
    {
        // 使用通配符替换模板内容
        $templateArr = json_decode(file_get_contents(resource_path($this->path)), true);
        $this->templateArr = $this->replaceWildcard($templateArr);

        // 合并elementsFields
        if ($buildElementFields) {
            $this->templateArr['elements'][0]['fields'] = $this->elementFields;
        }

        return $this;
    }

    public function getTemplateArr(): array
    {
        return $this->templateArr;
    }
}
